import os
from dotenv import load_dotenv, find_dotenv
import pymongo
import json

# 加载 .env 文件中定义的环境变量
_ = load_dotenv(find_dotenv())

class MongoClient:
    def __init__(self):
        user = os.getenv('MONGO_USER')
        password = os.getenv('MONGO_PASSWORD')
        db = os.getenv('MONGO_DB')
        self.client = pymongo.MongoClient(username=user, password=password)
        self.db = self.client[db]

    def insert_one(self, table, data):
        self.db[table].insert_one(data)
        
    def find(self, table, query):
        return self.db[table].find(query)
    
    def remove(self, table, query):
        self.db[table].delete_many(query)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()

    def __del__(self):
        try:
            if hasattr(self, 'client') and self.client:
                self.client.close()
        except:
            pass
